<template>
  <div id="login-page" class="login-box">
    <div class="back-image">
      <img :src="sysBgImg" />
    </div>
    <div class="mark"></div>
    <div class="login-content-box">
      <div class="login-img">
        <img :src="iconImg" />
      </div>
      <div class="login-title">{{$t('message.login.otherTitle')}}</div>
      <div class="system-name">{{ systemName }}</div>
      <div class="type-box">
        <div
          class="type-item"
          :class="[loginType == 'pwd' && 'active']"
          @click="changeType('pwd')"
        >
          {{$t('message.login.passWordTitle')}}
        </div>
        <div
          class="type-item"
          :class="[loginType == 'phone' && 'active']"
          @click="changeType('phone')"
        >
          {{$t('message.login.yzmTitle')}}
        </div>
      </div>
      <div class="input-box" v-if="loginType == 'pwd'">
        <el-input
          class="input-item"
          v-model="loginForm.account"
          :placeholder="$t('message.placeholder.pleaseAccount')"
          @keyup.enter="handleLogin"
        ></el-input>
        <el-input
          class="input-item"
          v-model="loginForm.passWord"
          type="password"
          :placeholder="$t('message.placeholder.pleasePassword')"
          @keyup.enter="handleLogin"
        ></el-input>
      </div>
      <div class="input-box" v-if="loginType == 'phone'">
        <el-input
          class="input-item"
          v-model="loginForm.account"
          :placeholder="$t('message.placeholder.pleaseAccount')"
          @keyup.enter="handleLogin"
        ></el-input>
        <div class="phone-box">
          <el-input
            class="input-item"
            v-model="loginForm.yzm"
            :placeholder="$t('message.placeholder.pleaseInputYzm')"
            @keyup.enter="handleLogin"
            :maxlength="6"
          ></el-input>
          <div class="phone-button" @click="sendYzm">{{ yzmText }}</div>
        </div>
      </div>
      <div
        class="login-button"
        :class="[
          (!loginForm.account || !(loginForm.yzm || loginForm.passWord)) &&
            'button-disable',
        ]"
        @click="handleLogin"
      >
        {{$t('message.login.loginBtn')}}
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import {
  ref,
  reactive,
  toRefs,
  watch ,
  onMounted,
  getCurrentInstance,
  onUnmounted
} from 'vue' 
import type { ComponentInternalInstance } from 'vue'
import * as dd from 'dingtalk-jsapi'
import { useRouter,useRoute } from "vue-router"
import logo from '@/assets/common/img/logo.png'
import { getPhone, getDomain } from '@/api/login.js'
import { setSessionStore } from '@/utils/store.js'
import useUserInfoStore from '@/store/userInfo.js'
import { useHookI18n } from '@/hooks/i18n'
const { locale,$t } = useHookI18n()
const userStore  = useUserInfoStore()
// import bulletinDialog from '@/utils/bulletin.js'
const instance: any = getCurrentInstance() as ComponentInternalInstance;
const proxy: any = instance.proxy as any; // 访问 proxy 属性
const router = useRouter();
const route = useRoute();
const emit = defineEmits([""])
const props = defineProps({

})
const loginType = ref('pwd')
const logoImg = ref(userStore?.tenantInfo?.logo || logo)
const iconImg = ref(userStore?.tenantInfo?.icon || logo)
const systemName = ref(userStore?.tenantInfo?.systemName || '')
const sysBgImg = ref(userStore?.tenantInfo?.bgImg || '')
const loginForm = ref({
  account: '',
  passWord: '',
  yzm: '',
})
const pwdType = ref('password')
const time = ref(180)
const isStartTime = ref(false)
const yzmText = ref($t('message.login.getVeriCode'))
const yzmInterval = ref(null)
const namecodelen = ref(6)
const submitLoading = ref(false)
const usertenantList = ref([])

onMounted(()=>{
  setSessionStore({ name: 'mobileRouterList', content: [] })
  if(userStore.access_token){
    router.push({ path:'/mobile/index' })
  }
  if (!userStore?.tenantInfo) {
    getDomainHandle()
  }
})
onUnmounted(()=>{
  if (yzmInterval.value) {
      clearInterval(yzmInterval.value)
    }
})
async function getDomainHandle() {
  try {
    const res = await getDomain()
    if (res.data && res.data.code == 0) {
      if (res.data.data) {
        if (res.data.data.name) {
          document.title = res.data.data.name || $t('message.worryFreeDocument')
        }
        if (res.data.data.logo) {
          logoImg.value = res.data.data.logo
        }
        if (res.data.data.icon) {
          iconImg.value = res.data.data.icon
        }
        if (res.data.data.systemName) {
          document.title = res.data.data.systemName
          systemName.value = res.data.data.systemName
        }
        if (res.data.data.bgImg) {
          sysBgImg.value = res.data.data.bgImg
        }
        userStore.setTenantInfo(res.data.data)
      } else {
        router.push({ path: '/404' })
      }
    } else {
    }
  } catch (error) {
    console.log(error)
  }
}
function changeType(type) {
  loginType.value = type
  loginForm.value = {
    account: '',
    passWord: '',
    yzm: '',
  }
}
function handleLogin() {
  if (submitLoading.value) return
  let newForm = {}
  newForm.password = loginForm.value.passWord
  newForm.code = loginForm.value.yzm
  newForm.loginType = loginType.value == 'pwd' ? 'namepass' : 'phone'
  if (loginType.value == 'pwd') {
    newForm.username = loginForm.value.account
  } else {
    newForm.phone = loginForm.value.account
  }
  if (!loginForm.value.account.trim()) {
    if (loginType.value == 'pwd') {
      proxy.$mobileMessage({
        type: 'warning',
        text: $t('message.placeholder.pleaseAccount'),
      })
    } else {
      proxy.$mobileMessage({
        type: 'warning',
        text: $t('message.placeholder.pleasePhone'),
      })
    }
    submitLoading.value = false
    return
  }
  if (loginType.value == 'pwd' && !loginForm.value.passWord.trim()) {
    submitLoading.value = false
    proxy.$mobileMessage({
      type: 'warning',
      text: $t('message.placeholder.pleasePassword'),
    })
    return
  }
  if (loginType.value == 'phone' && !loginForm.value.yzm.trim()) {
    submitLoading.value = false
    proxy.$mobileMessage({
      type: 'warning',
      text: $t('message.placeholder.pleaseInputYzm'),
    })
    return
  }
  submitLoading.value = true
  userStore.LoginByUsername( Object.assign({}, newForm)).then((data) => {
    getTenantByUserList(data)
  })
  .catch(() => {
    refreshCode()
    submitLoading.value = false
  })
}
function sendYzm() {
  if (isStartTime.value) return
  proxy.$message.closeAll()
  isStartTime.value = true
  if (yzmInterval.value) {
    clearInterval(yzmInterval.value)
  }
  if (!loginForm.value.account.trim()) {
    isStartTime.value = false
    proxy.$mobileMessage({
      type: 'warning',
      text: $t('message.placeholder.pleasePhone'),
    })
    return
  }
  getPhone({ phone: loginForm.value.account })
    .then(({ data }) => {
      if (data.code === 0) {
        let newTime = time.value
        newTime--
        yzmText.value = newTime + 's'
        yzmInterval.value = setInterval(() => {
          newTime--
          if (newTime <= 0) {
            clearInterval(yzmInterval.value)
            isStartTime.value = false
            yzmText.value = $t('message.login.getVeriCode')
          }
          yzmText.value = newTime + 's'
        }, 1000)
      }
    })
    .catch((err) => {
      isStartTime.value = false
      refreshCode()
    })
}
function refreshCode() {
  loginForm.value.yzm = ''
}
// 获取该用户下所有的租户列表
function getTenantByUserList(data) {
  let list = []
  if (data.userDto && data.userDto.tenants) {
    list = data.userDto.tenants
    if (list.length > 0) {
      // 只有一个租户直接进去
      if (list.length == 1) {
        userStore.setSwitchTenant(false)
        setUserInfoData(data)
      } else {
        userStore.setSwitchTenant(true)
        router.push({ path: '/mobile/index' })
      }
    }
  }
}
// 加入成功后写入数据
function setUserInfoData (data) {
  if(data) {
    userStore.batchSetStore(data,['access_token','expires_in','refresh_token','userInfo','roles','permissions','tenantId'])
    userStore.setTenantInfo(data.userDto.tenant)
    getDomainHandle()
    router.push({ path: '/mobile/index' });
  }
}
// 选择租户登录
function switchTenant (list) {
  proxy.$loginForm({
    successClose: false,
    switchTenant: true,
    switchList: list,
    afterLogin: (dialog, res) => {
      // 是否需要公告
      // bulletinDialog.install()
      dialog.handleClose()
      router.push({ path: '/mobile/index' })
    },
  })
}
</script>


<style lang="scss" scoped>
.login-box {
  padding: 5.0625rem 2rem 0px;
  position: relative;
  .back-image {
    height: 15rem;
    position: absolute;
    left: 0px;
    top: 0%;
    z-index: -1;
    width: 100%;
    // -webkit-transform: translateY(-50%);
    // transform: translateY(-50%);
    img {
      width: 100%;
      height: 15rem;
      z-index: 0;
    }
  }
  .mark {
    position: absolute;
    left: 0px;
    top: 0px;
    z-index: 1;
    width: 100%;
    height: 15rem;
    background: -webkit-gradient(
      linear,
      left top,
      left bottom,
      from(transparent),
      to(#fff)
    );
    background: linear-gradient(transparent, #fff);
  }
  .login-content-box {
    position: relative;
    z-index: 12;
    .login-img {
      width: 3rem;
      height: 3rem;
      border-radius: 0.75rem;
      box-shadow: 0px 10px 25px 0px rgba(30, 111, 255, 0.2);
      overflow: hidden;
      margin-bottom: 1.25rem;
      img {
        width: 3rem;
        height: 3rem;
      }
    }
    .login-title {
      font-size: 1.5rem;
      color: #363b4c;
      @include SourceHanSansCN-Bold;
    }
    .system-name {
      font-size: 1.5rem;
      color: #363b4c;
      @include SourceHanSansCN-Bold;
      margin-bottom: 3.75rem;
      text-overflow: ellipsis;
      white-space: nowrap;
      overflow: hidden;
    }
    .type-box {
      display: flex;
      margin-bottom: 1.5rem;
      .type-item {
        font-size: 1rem;
        color: #3d3d3d;
        @include SourceHanSansCN-Regular;
        position: relative;
        height: 2.25rem;
        line-height: 2.25rem;
      }
      .active {
        color: #1e6fff;
        @include SourceHanSansCN-Bold;
        &::before {
          position: absolute;
          content: '';
          bottom: 0px;
          height: 0.1875rem;
          width: 100%;
          background: #1e6fff;
          border-radius: 0.3125rem 0 0.3125rem 0;
        }
      }
      .type-item + .type-item {
        margin-left: 2.75rem;
      }
    }
    .input-box {
      height: 9rem;
      .input-item {
        margin-bottom: 1.5rem;
        height: 3rem;
        background-color: #f2f7ff;
        line-height: 3rem;
        border-radius: 0.375rem;
        overflow: hidden;
        ::v-deep(input){
          border: none !important;
          background-color: transparent !important;
        }
      }
      .phone-box {
        display: flex;
        .input-item {
          margin-bottom: 1.5rem;
          height: 3rem;
          background-color: #f2f7ff;
          line-height: 3rem;
          border-radius: 0.375rem;
          overflow: hidden;
          ::v-deep(input){
            border: none !important;
            background-color: transparent !important;
          }
        }

        .phone-button {
          background-color: #f2f7ff;
          border-radius: 0.375rem;
          margin-left: 0.75rem;
          margin-bottom: 1.5rem;
          height: 3rem;
          line-height: 3rem;
          min-width: 7rem;
          color: #1e6fff;
          text-align: center;
          @include SourceHanSansCN-Regular;
        }
      }
    }
    .login-button {
      margin-top: 2.5rem;
      color: #fff;
      font-size: 0.875rem;
      text-align: center;
      line-height: 3rem;
      @include SourceHanSansCN-Medium;
      height: 3rem;
      background: #1e6fff;
      border-radius: 0.375rem;
    }
  }
}
.button-disable {
  background: #8eb7ff !important;
}
</style>
